<?php

App::uses('AppModel', 'Model');

class OffersLocation extends AppModel {
        
    public $name     = 'OffersLocation';
    public $useTable = 'offers_locations';
    
    public $hasOne = array(
        'Tax' => array(
            'foreignKey' => false,
            'conditions' => array('Tax.effective_date <=' => 'OffersLocation.start'),
            'order'      => 'Tax.effective_date DESC',
            'limit'      => 1
        )
    );
    
    public $belongsTo = array('Location');
    
    public function afterFind($results, $primary=false) {
        $results = parent::afterFind($results, $primary);
        
        if (! empty($results)) {
            
            foreach ($results as &$row) {
                if (empty($row['OffersLocation']['location_id'])) {
                    continue;
                }
                if (empty($row['Location'])) {
                    $row['Location'] = Set::extract('Location', $this->Location->find('first', array(
                        'fields' => array('Location.*'),
                        'conditions' => array(
                            'Location.id' => $row['OffersLocation']['location_id']
                        ),
                        'recursive' => 1
                    )));
                }
                
                $p = $this->calculatePrice($row);
                $row['OffersLocation']['price']      = $p->price;
                $row['OffersLocation']['num_months'] = $p->numMonths;
            }
        }

        return $results;
    }
    
    public function calculatePrice($data) {
        $price = 0;
        $numMonths = 1;
        
        if ( !empty($data['Location']) && !empty($data['OffersLocation']) ) {
            $locPrice = $data['Location']['price'];
            
            $start = $data['OffersLocation']['start'];
            $end   = $data['OffersLocation']['end'];
			$numMonths = calculateNumMonths($start, $end);
            
            $price = $numMonths * (float)$data['Location']['rent_price'];
        }
        
        return (object)array(
            'price'     => $price,
            'numMonths' => $numMonths
        );
    }
}
